#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int get_listen_fd(char *);

int main(int argc, char *argv[])
{
    int tcp_fd = get_listen_fd(argv[1]);

    struct sockaddr_in client_addr;
    socklen_t len = sizeof(struct sockaddr_in);
    int con_fd = accept(tcp_fd, (struct sockaddr *)&client_addr, &len);


    close(con_fd);
    close(tcp_fd);
    return 0;
}

int get_listen_fd(char *port)
{
    int tcp_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (tcp_fd < 0)
    {
        perror("socket fail");
        exit(-1);
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(port));
    inet_pton(AF_INET, "0.0.0.0", &server_addr.sin_addr);
    
    int on = 1;
    setsockopt(tcp_fd,SOL_SOCKET,SO_REUSEADDR,(void*)&on,sizeof(on));
    int ret = bind(tcp_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));

    listen(tcp_fd, 1);

    return tcp_fd;
}
